import sys, os, csv
import subprocess
import time
from subprocess import Popen

class Experiment:

    def __init__(self, num_clients, time):
        self.process_list = []
        self.num_clients = num_clients
        self.time = time / 10
        self.bandwidth = 0

    def run(self):
        for i in range(0,self.time):
            int_bandwidth = 0
            for j in range(0,self.num_clients):
                self.process_list.append(Popen(["python", "socketSend.py"], stdout=subprocess.PIPE))
            for j in range(0,self.num_clients):
                self.process_list[j].wait()
                strings = self.process_list[j].stdout.readlines()
                sum_line = strings[0]
                p = csv.reader([sum_line])
                for row in p:
                    int_bandwidth += float(row[1])
                    #self.bandwidth = self.bandwidth / 1000000
                    #print "%.02f Mb/s"%bandwidth
            self.process_list = []
            self.bandwidth += int_bandwidth
            print "%d(%d): %.02f(%.02f)"%(self.num_clients, (i+1), (self.bandwidth / (i+1)), (int_bandwidth))
            time.sleep(2)

    def getResult(self):
        return self.bandwidth / self.time

if __name__ == '__main__' :

    num_procs = [1,2,4,6,8,12,16]
    load = [1,4,8,12,16,20]
    results = {}
    ret = 0
    
    for i in num_procs:
        os.system('ssh root@pc22 "cd naptpt; ./makesys.sh %d naptpt && make -j" > /dev/null 2>> ./error.log'%i)
        if(ret == 0):
            print "Make with %d processors succeeded."%i
        else:
            exit("Make with %d processors failed, exiting."%i)
        line = []
        for j in load:
            ret = os.system('ssh root@pc22 "cd naptpt; screen -d -m ./naptpt"')
            if(ret == 0):
                print "Execution of naptpt succeeded for load %d."%j
            else:
                exit("Execution failed with load %d."%j)
            ret = os.system('ssh pc3.cias.utexas.edu "screen -d -m python Server.py"')
            if(ret == 0):
                print "Execution of server succeeded for load %d."%j
            else:
                exit("Execution failed with load %d."%j)
            time.sleep(5)
            exp = Experiment(j, 180)
            exp.run()
            line.append(exp.getResult())
            ret = os.system('ssh pc3.cias.utexas.edu "killall -9 python"')
            if(ret == 0):
                print "Successfully killed server for load %d."%j
            else:
                exit("Kill failed with load %d."%j)
            ret = os.system('ssh root@pc22 "killall -9 naptpt"')
            if(ret == 0):
                print "Successfully killed naptpt for load %d."%j
            else:
                exit("Kill failed with load %d."%j)
            time.sleep(10)
        results[i] = line
    
    outfile = open("naptpt_loads.dat", 'w')
    outfile.write(str(results))
                  
